import http from './http.js';
import config from '../mp.config.js';


export function request(opts) {
    const { url, method='get', data, headers={},noRefetch } = opts;
    
	return new Promise(async (resolve, reject) => {
        http({url,method,data,headers:headers}).then(async (res) => {

            if(res.data.code === 1001 || res.data.code === 1003) {
                //请求失败，没有传noRefetch，则重新请求。传了noRefetch，则不重新请求
                if(!noRefetch) {
                    // 删除过期的token
                    // localStorage.removeItem('token');
                    // token过期，重新获取token
                    let token=await refreshToken(res.token);
                    resolve(request({url,method,data,headers:{...headers,token},noRefetch:true}));
                }
            }else{
                //请求失败，没有传noRefetch，则重新请求。传了noRefetch，则不重新请求
                if(res.status==404 && !noRefetch || res.data.code==1 && !noRefetch) {
                    // 重新请求
                    resolve(request({url,method,data,headers,noRefetch:true}));
                }else{
                    resolve(res.data);
                }
            }

        }).catch(err => {
            reject(err)
        })
	});

}

//刷新token
export function refreshToken(token) {
	return new Promise((resolve, reject) => {
        http({url:config.route.refreshToken,method:'post',data:{token}}).then(res => {
            if(res.data.code == 0) {
                localStorage.setItem('token', res.data.data.token);
            }
            resolve(res.data.data.token)
        }).catch(err => {
            reject(err)
        })
	});
}


/**
 * json对象转url参数
 * @param data 对象
 */
export function parseParams(data) {
	var result = [];
	for (var key in data) {
		var value = data[key];
		if (value != null && value != "") {
			if (value.constructor == Array) {
				value.forEach(function (_value) {
					result.push(key + "=" + _value);
				});
			} else {
				result.push(key + '=' + value);
			}
		} else {
			result.push(key + '=' + value);
		}
	}
	return '?' + result.join('&');
}
